<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="演讲主题" prop="programmesTitle">
        <el-input
          v-model="queryParams.programmesTitle"
          placeholder="请输入演讲主题"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="演讲者姓名/拼音" prop="speakerName">
        <el-input
          v-model="queryParams.speakerName"
          placeholder="请输入演讲者姓名/拼音"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会场" prop="placeId">
        <el-select v-model="queryParams.placeId" filterable remote reserve-keyword placeholder="请选择会场" :remote-method="queryRemoteMethod" :loading="queryPlaceIdLoading" clearable style="width: 240px">
          <el-option
            v-for="item in queryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="会场环节" prop="matterId">
        <el-select v-model="queryParams.matterId" filterable remote reserve-keyword placeholder="请选择会场环节" :remote-method="queryRemoteMatter" :loading="queryMatterLoading" clearable style="width: 240px">
          <el-option
            v-for="item in queryOptions2"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" />
      <el-table-column label="演讲主题" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="演讲嘉宾" prop="speakerList">
        <template slot-scope="scope">
          <span>{{ scope.row.speakerList | getFullName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会议环节" prop="matterTitle" />
      <el-table-column label="会场" prop="placeName" />
      <el-table-column label="演讲日期" align="center" prop="startDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时长" prop="duration" />
      <el-table-column label="结束时间" align="center" prop="endTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" append-to-body :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="90px" style="height: 500px; overflow: auto">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基础信息" name="first">
            <el-form-item label="会场环节" prop="matterId">
              <el-select v-model="form.matterId" filterable remote reserve-keyword placeholder="请选择会场环节" :remote-method="queryRemoteMatter3" :loading="queryMatterLoading3" style="width: 370px">
                <el-option
                  v-for="item in queryOptions3"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="演讲主题" prop="title">
              <el-input v-model="form.title" placeholder="请输入演讲主题" clearable />
            </el-form-item>
            <el-form-item label="演讲嘉宾" prop="unitList">
              <el-select v-model="form.unitList" multiple filterable remote reserve-keyword placeholder="请选择演讲嘉宾" :remote-method="remoteMethod" :loading="unitLoading" @change="handleUnitChange" style="width: 370px">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-time-picker v-model="form.startTime" placeholder="请选择开始时间" format="HH:mm" value-format="timestamp" @change="handleStartTimeChange" clearable style="width: 370px" />
            </el-form-item>
            <el-form-item label="演讲时长" prop="duration">
              <el-input-number v-model="form.duration" controls-position="right" :min="1" :max="1000" @change="handleChange" style="width: 370px"></el-input-number>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-time-picker v-model="form.endTime" placeholder="请选择结束时间" disabled format="HH:mm" value-format="timestamp" clearable style="width: 370px" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="嘉宾头衔" name="second">
            <el-collapse v-model="activeNames">
              <el-collapse-item title="演讲嘉宾头衔" name="1">
                <template v-for="(item) in form.programmesSpeakerList">
                  <el-form-item :label="item.speakerName">
                    <el-input v-model="item.speakerTitle" placeholder="请输入演讲嘉宾头衔" @change="handleProgrammesSpeakerTitleChange(item)" clearable />
                  </el-form-item>
                </template>
              </el-collapse-item>
            </el-collapse>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {addProgramme, delProgramme, listProgrammes, updateProgramme} from "@/api/meetingManagement/programmes";
import {listPlace} from "@/api/meetingManagement/place";
import {listMatter} from "@/api/meetingManagement/matter";
import {listSpeaker} from "@/api/meetingManagement/speaker";

export default {
  name: "SpeechTopic",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        speakerName: undefined,
        programmesTitle: undefined,
        placeId: undefined,
        meetId: undefined,
        matterId: undefined
      },
      // 表单参数
      form: {
        duration: null,
        startTime: null,
        endTime: null,
        matterId: null,
        title: null,
        programmesSpeakerList: []
      },
      // 表单校验
      rules: {
        matterId: [
          { required: true, message: "会场环节不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "演讲主题不能为空", trigger: "blur" }
        ],
        startTime: [
          { type: 'date', required: true, message: "开始时间不能为空", trigger: "change" }
        ],
        duration: [
          { required: true, message: "演讲时长不能为空", trigger: "blur" }
        ],
        endTime: [
          {  type: 'date', required: true, message: "结束时间不能为空", trigger: "change" }
        ]
      },
      dialogVisible: false,
      queryPlaceIdLoading: false,
      queryOptions: [],
      queryMatterLoading: false,
      queryOptions2: [],
      queryOptions3: [],
      queryMatterLoading3: false,
      unitLoading: false,
      options: [],
      activeName: 'first',
      activeNames: ['1']
    }
  },
  mounted() {
    this.queryParams.meetId = this.$route.params && this.$route.params.id
    this.getList()
    this.queryRemoteMethod()
    this.queryRemoteMatter()
  },
  filters: {
    getFullName: function(value) {
      if (value) {
        return value.map(item => item.fullName).join(',')
      } else {
        return ''
      }
    }
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true
      listProgrammes(this.addDateRange(this.queryParams)).then(response => {
          this.roleList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    remoteMethod(query) {
      if (query !== '') {
        this.unitLoading = true;
        listSpeaker({
          name: query,
          pageNum: 1,
          pageSize: 200,
          meetId: this.queryParams.meetId
        }).then(response => {
          this.options = response.rows
          this.options.forEach((item) => {
            item.name = item.lastName + item.firstName
          })
          this.unitLoading = false
        })
      } else {
        this.options = [];
      }
    },
    queryRemoteMethod(query) {
      if (query !== '') {
        this.queryPlaceIdLoading = true;
        listPlace({
          name: query,
          pageNum: 1,
          pageSize: 200,
          meetId: this.queryParams.meetId
        }).then(response => {
          this.queryOptions = response.rows
          this.queryPlaceIdLoading = false
        })
      } else {
        this.queryOptions = [];
      }
    },
    queryRemoteMatter(query) {
      if (query !== '') {
        this.queryMatterLoading = true;
        listMatter({
          name: query,
          pageNum: 1,
          pageSize: 200,
          meetId: this.queryParams.meetId
        }).then(response => {
          this.queryOptions2 = response.rows
          this.queryMatterLoading = false
        })
      } else {
        this.queryOptions2 = [];
      }
    },
    queryRemoteMatter3(query) {
      if (query !== '') {
        this.queryMatterLoading3 = true;
        listMatter({
          name: query,
          pageNum: 1,
          pageSize: 200,
          meetId: this.queryParams.meetId
        }).then(response => {
          this.queryOptions3 = response.rows
          this.queryMatterLoading3 = false
        })
      } else {
        this.queryOptions3 = [];
      }
    },
    handleUnitChange(val) {
      let list = []
      if (val?.length > 0) {
        val.forEach(item => {
          this.options.forEach(item2 => {
            if (item2.id === item) {
              let json = {
                speakerId: item2.id,
                speakerName: item2.name,
                meetId: this.queryParams.meetId
              }
              list.push(json)
            }
          })
        })
      } else {
        list = []
      }
      this.form.programmesSpeakerList = list
    },
    // 取消按钮
    cancel() {
      this.dialogVisible = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields()
        }
      })
      this.activeName = 'first'
      this.form = {
        duration: null,
        startTime: null,
        endTime: null,
        matterId: null,
        title: null,
        programmesSpeakerList: []
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        speakerName: undefined,
        programmesTitle: undefined,
        placeId: undefined,
        meetId: this.$route.params && this.$route.params.id,
        matterId: undefined
      }
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.queryRemoteMatter3()
      this.remoteMethod()
      this.title = "新增演讲主题"
      this.dialogVisible = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.queryRemoteMatter3()
      this.remoteMethod()
      this.form = {...row}
      this.form.unitList = this.form.speakerList.map(item => item.speakerId)
      this.title = "修改演讲主题"
      setTimeout(() => {
        this.handleTitle()
      }, 300)
      this.dialogVisible = true
    },
    handleTitle() {
      if (this.options?.length > 0) {
        // 使用 $set 或重新赋值确保响应式
        this.$set(this.form, 'programmesSpeakerList',
          this.form.speakerList.map(item => {
            const speaker = this.options.find(sel => item.speakerId === sel.id);
            if (speaker) {
              console.log("speaker", speaker, item, item.fullName.replace(speaker.name, ''))
              return {
                ...item,
                speakerName: speaker.name,
                speakerTitle: item.fullName.replace(speaker.name, '')
              };
            }
            return item;
          })
        )
        console.log("111111111", this.form.programmesSpeakerList)
      }
    },
    handleClick(tab) {
      this.activeName = tab.name
    },
    handleProgrammesSpeakerTitleChange(item) {
      item.fullName = item.speakerName + item.speakerTitle
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.meetId = this.queryParams.meetId
          if (this.form.id != undefined) {
            updateProgramme(this.form).then(response => {
              this.$modal.msgSuccess(response.msg || "修改成功")
              this.dialogVisible = false
              this.getList()
            })
          } else {
            addProgramme(this.form).then(response => {
              this.$modal.msgSuccess(response.msg || "新增成功")
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id
      this.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(function() {
        return delProgramme(roleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 当开始时间改变时，也要重新计算结束时间
    handleStartTimeChange(val) {
      if (val && this.form.duration) {
        this.calculateEndTime();
      }
    },

    // 当时长改变时，重新计算结束时间
    handleChange() {
      if (this.form.startTime) {
        this.calculateEndTime();
      } else {
        this.$message.warning('请先选择开始时间');
      }
    },

    // 统一的结束时间计算方法
    calculateEndTime() {
      if (this.form.startTime && this.form.duration) {
        // 将分钟转换为毫秒
        const durationInMs = this.form.duration * 60 * 1000;
        // 计算结束时间
        this.form.endTime = this.form.startTime + durationInMs;
      }
    }
  }
}
</script>
<style scoped lang="scss">

</style>
